<template>
    <div>
        <el-row>
            <el-card>
                <div style="margin-top: 15px;" id="app">
                    <el-form :inline="true" :model="selectForm" class="demo-form-inline">
                        <el-form-item>
                            <el-input v-model="selectForm.id" placeholder="请输入用户名"></el-input>
                        </el-form-item>
                            <el-form-item>
                                <el-button plain type="primary" @click="select()">查询</el-button>
                            </el-form-item>
                        </el-form>
                        <!--          选中框-->
                        <el-table
                                v-loading="loading"
                                :data="tableData"
                                @selection-change="handleSelectionChange"
                                style="width: 100%">
                            <el-table-column
                            type="selection"
                            width="55">
                            </el-table-column>

                            <el-table-column prop="username" label="用户名" sortable width="300"></el-table-column>
                            <el-table-column prop="password" label="密码" sortable width="300"></el-table-column>
                            <el-table-column align="right" width="300">
                                <template slot="header">
                                    <el-button type="primary" @click="exportExcel()" size="mini" plain>导出所选中信息
                                    </el-button>
                                </template>
                                <template slot-scope="scope">
                                    <el-button size="mini" type="primary" plain @click="edit=true"
                                               v-if="scope.row&&update_button==1">修改
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <!--          表格完成-->
                        <!--          分页-->
                        <el-pagination
                                style="margin: 15px 0px;"
                                prev-text="上一页" next-text="下一页" background
                                layout="prev, pager, next, sizes, jumper, total"
                                :page-sizes="[5,10,20,40,100,500,50000]"
                                :page-size="pageSize"
                                :total="total"
                                :current-page="pageNow"
                                @current-change="findPage"
                                @size-change="findSize">
                        </el-pagination>

                        <!--          修改用户-->
                        <el-dialog title="修改用户信息" :visible.sync="edit" width="50%">
                            <el-form ref="eform" label-width="80px" :model="eform">
                                <el-form-item label="用户名" prop="username">
                                    <el-input v-model="eform.username" disabled></el-input>
                                </el-form-item>
                                <el-form-item label="密码" prop="password">
                                    <el-input v-model="eform.password"></el-input>
                                </el-form-item>
                            </el-form>
                            <span slot="footer" class="dialog-footer">
            <el-button @click="edit = false">取 消</el-button>
            <el-button type="primary" @click="edit = false,updateUser(eform)">确 定</el-button>
          </span>
          </el-dialog>
           </div>
            </el-card>
        </el-row>


    </div>
</template>

<script>
    import XLSX from 'xlsx'
    import baseUrl from '@/utils/global.js'
    var list = []

    export function validateAccountNumber(str) {
        const reg = /^([1-9]{1})$/
        return reg.test(str)
    }

    export default {

        data() {
            let num = /^(0|\+?[1-9][0-9]*)$/
            let isNum = (rule, value, callback) => {
                if (!num.test(value)) {
                    return callback(new Error('格式错误'))
                } else {
                    callback()
                }
            }
            let percent = /^(?:[1-9]?\d|100)$/
            let isPercent = (rule, value, callback) => {
                if (!percent.test(value)) {
                    return callback(new Error('请输入0-100的整数'))
                } else {
                    callback()
                }
            }
            return {
                fileList: [],
                edit: false,
                update_button: 1,
                total: 0,//总页数，从后台查询
                pageNow: 1,//当前页数，默认为1
                pageSize: 5,//当前页显示的数据条数，默认为5
                loading: false,
                tableData: null,
                eform: {
                    id: '',
                    username: '',
                    password: ''
                },
                selectForm: {
                    id: ''
                }

            }
        },
        methods: {
            //查询
            findAllTableDataByPage() {
                let pageRequest = {
                    pageNow: this.pageNow,
                    pageSize: this.pageSize
                };
                this.$http.user.findPage(pageRequest).then((res) => {
                    // console.log(res.data)
                    this.tableData = res.data
                    this.total = res.total
                })
            },
            impotExcel(file, fileList) {
                let that = this
                let f = file.raw
                let reader = new FileReader()
                reader.onload = function (e) {
                    let data = new Uint8Array(e.target.result)
                    var workbook = XLSX.read(data, {type: 'array'})
                    let json = XLSX.utils.sheet_to_json(workbook.Sheets.Sheet1) // 取第一个sheet
                    that.jsonData = json
                    x = json
                    that.jsonStr = JSON.stringify(json)
                    that.tableData = json
                }
                //this.$http.post("/studentMessage/save",message);
                reader.readAsArrayBuffer(f)
                this.$message({
                    message: 'Excel内信息已展示至表格内',
                    type: 'success'
                })
                this.delete_button = 0
                this.update_button = 0
            },
            getMessage() {
                this.$confirm('此操作将保存进数据库, 是否继续?', '提示', {
                    confirmButtonText: '继续',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$message({
                        type: 'success',
                        message: '保存成功!'
                    })
                    this.$http.area.saveFromExcel(this.jsonData).then(function (resp) {
                        if (resp.code == 2000) location.reload();
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消保存'
                    })
                })
            },
            findPage(page) {
                // console.log('当前页数：' + page)
                this.pageNow = page
                this.findAllTableDataByPage()
            },
            findSize(size) {
                // console.log('当前页面记录条数：' + size)
                this.pageSize = size
                this.findAllTableDataByPage()
            },
            handleSelectionChange(val) {
                this.multipleSelection = val
                //console.log(val)
            },
            //更新
            updateUser(formName) {
                // console.log(this.eform)
                const _this = this
                this.$http.user.update(this.eform).then((resp) => {
                    if (resp.code == 2000) _this.$message.success('修改成功')
                    location.reload()
                })
            },
            select() {
                const _this = this
                this.$http.user.findAll().then((resp) => {
                    let list = []
                    for (let i=0;i<resp.data.length;i++){
                        if (resp.data[i].username.indexOf(this.selectForm.id)==0 ){
                            list.push(resp.data[i])
                        }
                    }
                    this.tableData = list
                    console.log(this.tableData)
                })
                console.log(this.selectForm.id)

            },
            exportExcel() {
                //创建book
                var wb = XLSX.utils.book_new()
                //json转sheet
                var ws = XLSX.utils.json_to_sheet(this.multipleSelection, {})
                //设置列宽
                ws['!cols'] = [
                    {width: 15},
                    {width: 15},
                    {width: 30}
                ]
                var timestamp = new Date().getTime()
                //sheet写入book
                XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
                //输出
                XLSX.writeFile(wb, 'file_' + timestamp + '.xlsx')
            }
        },
        created() {
            const _this = this
            _this.findAllTableDataByPage()
        }

    }
</script>

<style scoped>

</style>
